﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Configuration;
using MainConsoleService.MergeOrder;
using MainConsoleService.OrderDownService;
using MainConsoleService.Common;
using MainConsoleService.DownOrderToERP;
using MainConsoleService.PromotionOrderDo;
using MainConsoleService.PrePackaged;

namespace DownOrderApplication
{
    public partial class DownOrderAppService : Form
    {
        string isAuto = "";
        public DownOrderAppService()
        {
            InitializeComponent();
        }

        private static readonly string logPath = AppDomain.CurrentDomain.BaseDirectory;

        private void DownOrderService_Load(object sender, EventArgs e)
        {
            isAuto = ConfigurationManager.AppSettings["isAuto"].Trim();
            if (!Directory.Exists(logPath + "log"))
            {
                Directory.CreateDirectory(logPath + "\\log");
            }
            notifyIcon1.BalloonTipText = "系统服务已经开启，系统服务开始运行!";
            notifyIcon1.BalloonTipTitle = "CocoNut OrderDownTool Service";
            notifyIcon1.ShowBalloonTip(2);
            this.Visible = false;
            SetServiceStatus(isAuto);         
        }      

        private void SetServiceStatus(string status)
        {
            time_downorder.Enabled = status == "1" ? true : false;
            time_sendGoods.Enabled = status == "1" ? true : false;
            time_Stock.Enabled = status == "1" ? true : false;
        }
        private bool CheckServiceStatus()
        {
            isAuto = ConfigurationManager.AppSettings["isAuto"].Trim();
            return isAuto=="1"?true:false; 
        }

        private void downHandToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmServiceTookKit fd = new FrmServiceTookKit();
            fd.ShowDialog();
           
        } 

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
            Application.Exit();
        }

        private void time_downorder_Tick(object sender, EventArgs e)
        {
            if (bgw_DownOrder.IsBusy)
                return;
            bgw_DownOrder.RunWorkerAsync();
        }

        private void bgw_DownOrder_DoWork(object sender, DoWorkEventArgs e)
        {
            if (CheckServiceStatus())
            {
                e.Result = DownOrderToERP(e);
            }
            else
            {
                WriteSysLog.Log("ServerLog",string.Format("订单下载服务停止！\r\n{0}",System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            }
        }

        private object DownOrderToERP(DoWorkEventArgs e)
        {
            bool isOk = false;
            int hour = 0;
            string bgDateTime = "";
            string edDateTime = "";
            hour = System.DateTime.Now.Hour;
            if (hour >= 0 && hour < 12)
            {
                bgDateTime = System.DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") + " 17:00:00";
                edDateTime = System.DateTime.Now.ToString("yyyy-MM-dd") + " 12:00:00";
            }
            else
            {
                bgDateTime = System.DateTime.Now.ToString("yyyy-MM-dd") + " 10:00:00";
                edDateTime = System.DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00";
            }
            try
            {
                MergeOrder dmo = new MergeOrder();
                CocoNut.BLL.OrderDownService.T_ERP_ShopInfo bll = new CocoNut.BLL.OrderDownService.T_ERP_ShopInfo();
                List<CocoNut.Model.OrderDownService.T_ERP_ShopInfo> listModel = new List<CocoNut.Model.OrderDownService.T_ERP_ShopInfo>();
                listModel = bll.GetModelList(" IsAutoDown=1 ");
                foreach (CocoNut.Model.OrderDownService.T_ERP_ShopInfo model in listModel)
                {
                    switch (model.ShopNumber)
                    {                      
                        case 1:
                            TopTmallOrderDown tmall = new TopTmallOrderDown(model);
                            tmall.GetTradesSoldIncrementFromTop(DateTime.Parse(bgDateTime), DateTime.Parse(edDateTime), "WAIT_SELLER_SEND_GOODS",model);
                            tmall.DoRefundOrder(model, "WAIT_SELLER_AGREE");
                            tmall.DoRefundOrder(model, "SUCCESS");
                            break;
                        case 2:
                            PaiPaiOrderDown pp = new PaiPaiOrderDown(model);
                            pp.GetOrderList(bgDateTime, edDateTime, 1, model);
                           // pp.GetRefundOrderList(bgDateTime, edDateTime, 1, model);
                            break;
                        case 3:
                            JDOrderDown jd = new JDOrderDown(model);
                            jd.buyordersearch360(bgDateTime, edDateTime, 1, model.OrderCount.Value);
                            //jd.JdPopaFsRefundApply(bgDateTime, edDateTime, 1, 1); //退款订单
                            break;
                        case 9:
                            TopTmallOrderDown tmall9 = new TopTmallOrderDown(model);
                            tmall9.GetTradesSoldIncrementFromTop(DateTime.Parse(bgDateTime), DateTime.Parse(edDateTime), "WAIT_SELLER_SEND_GOODS",model);                            
                            tmall9.DoRefundOrder(model, "WAIT_SELLER_AGREE");
                            tmall9.DoRefundOrder(model, "SUCCESS");
                            break;
                        case 10:
                            ICBCOrderDown icbc = new ICBCOrderDown(model);
                            icbc.GetOrderList("", "", bgDateTime, edDateTime, "02", model);
                            //icbc.GetRefundOrder(model);
                            break;
                        case 13:
                            YhdOrderDown yhd = new YhdOrderDown(model);
                            yhd.yhd_orders_get(bgDateTime, edDateTime, 1, model.OrderCount.Value);
                           // yhd.yhd_orders_refund_abnormal_get(bgDateTime, edDateTime, 1); 
                            break;
                        case 14:
                            DangDangOrderDown dang = new DangDangOrderDown(model);
                            dang.GetOrderList(bgDateTime, edDateTime, "101", 1, model.OrderCount.Value, model);
                            // dang.GetDangdangRefundList(bgDateTime, edDateTime, 1, model.OrderCount.Value, model);
                            break;
                        case 15:
                            VipShopOrderDown vip = new VipShopOrderDown(model);
                            vip.GetVipShopOrders(bgDateTime, edDateTime, 1, model);
                            //vip.DoRefundOrderList(bgDateTime, edDateTime, 1, model);
                            break;
                        case 17:
                            SuningOrderDown so = new SuningOrderDown(model);
                            so.GetOrderList(bgDateTime, edDateTime, 1, model.OrderCount.Value);
                           // so.GetSuningRefundList(bgDateTime, edDateTime, 1, model.OrderCount.Value);
                            break;                      
                    }
                    if (model.IsMerge.Value)
                    {
                        dmo.DoMergeOrder(model.ShopNumber.Value);
                        isOk = true;                       
                    }
                    PromotionOrder po = new PromotionOrder();
                    po.DoPromotionOrder(model.ShopNumber.Value); //合并订单后，调用促销管理
                }
            }
            catch (Exception ex)
            {
                isOk = false;
                WriteSysLog.Log("ServerLog", string.Format("订单下载服务运作异常，异常信息{0},异常时间{1}\r\n", ex.Message, System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            }            
            return isOk;
        }

     

        private void time_Stock_Tick(object sender, EventArgs e)
        {
            if (bgw_OutStock.IsBusy)
                return;
            bgw_OutStock.RunWorkerAsync();
        }

        private void bgw_OutStock_DoWork(object sender, DoWorkEventArgs e)
        {
            if (CheckServiceStatus())
            {
                e.Result = OutStockInfo(e);
            }
            else
            {
                WriteSysLog.Log("ServerLog", string.Format("订单出库服务停止！\r\n{0}", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            }
        }

        private object OutStockInfo(DoWorkEventArgs e)
        {
            string errmsg = "";
            bool isOk = false;
            try
            {
                WriteSysLog.Log("OutStockLog", string.Format("订单出库服务开始运行，时间{0}\r\n", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
                CocoNut.BLL.OrderDownService.t_ddzb bll = new CocoNut.BLL.OrderDownService.t_ddzb();
                List<CocoNut.Model.OrderDownService.t_ddzb> ddzbList = bll.GetModelList("  hb_zt='否'and bgcz=1 and status!='已删除' and ck=0 order by pay_time  "); //无法自动发货的订单销售出库
                foreach (CocoNut.Model.OrderDownService.t_ddzb model in ddzbList)
                {
                    isOk = DownOrderCommon.OutStockByOrderId(model, ref errmsg);
                    if (isOk)
                    {
                        bll.UpdateMallOrderStockStatus(model.id, true, "自动出库", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    }
                }
            }
            catch (Exception ex)
            {
                isOk = false;
                WriteSysLog.Log("OutStockLog", string.Format("订单出库服务运作异常，异常信息{0},异常时间{1}\r\n", ex.Message, System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            }
            finally
            {
                if(isOk)
                    WriteSysLog.Log("OutStockLog", string.Format("订单出库服务结束运行，时间{0}\r\n", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));

            }
            return isOk;
        }

        private void time_sendGoods_Tick(object sender, EventArgs e)
        {
            if (bgw_sendGoods.IsBusy)
                return;
            bgw_sendGoods.RunWorkerAsync();
        }

        private void bgw_sendGoods_DoWork(object sender, DoWorkEventArgs e)
        {
            if (CheckServiceStatus())
            {
                e.Result = DoSendGoods(e);
            }
            else
            {
                WriteSysLog.Log("ServerLog", string.Format("订单发货服务停止！\r\n{0}", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            }
        }

        private object DoSendGoods(DoWorkEventArgs e)
        {
            bool isOk = false;
            try
            {
                CocoNut.Model.OrderDownService.T_ERP_ShopInfo yhdModel = new CocoNut.Model.OrderDownService.T_ERP_ShopInfo();
                CocoNut.BLL.OrderDownService.T_ERP_ShopInfo bll = new CocoNut.BLL.OrderDownService.T_ERP_ShopInfo();
                List<CocoNut.Model.OrderDownService.T_ERP_ShopInfo> listModel = new List<CocoNut.Model.OrderDownService.T_ERP_ShopInfo>();
                listModel = bll.GetModelList(" IsAutoDown=1 ");
               
                yhdModel = listModel.Find(u => u.ShopNumber == 13);
                YhdOrderDown yhdd = new YhdOrderDown(yhdModel);
                yhdd.SendLogisticsInfo();

                foreach (CocoNut.Model.OrderDownService.T_ERP_ShopInfo model in listModel)
                {
                    try
                    {
                        switch (model.ShopNumber)
                        {
                            case 1:
                                TopTmallOrderDown tmall = new TopTmallOrderDown(model);
                                tmall.SendLogisticsInfo(model);
                                break;
                            case 2:
                                PaiPaiOrderDown pp = new PaiPaiOrderDown(model);
                                pp.SendLogisticsInfo(model);
                                break;
                            case 3:
                                JDOrderDown jd = new JDOrderDown(model);
                                jd.SendLogisticsInfo();
                                break;
                            case 9:
                                TopTmallOrderDown tmall9 = new TopTmallOrderDown(model);
                                tmall9.SendLogisticsInfo(model);
                                break;
                            case 10:
                                ICBCOrderDown icbc = new ICBCOrderDown(model);
                                icbc.SendLogisticsInfo(model);
                                break;
                            case 13:
                                YhdOrderDown yhd = new YhdOrderDown(model);
                                yhd.SendLogisticsInfo();
                                break;
                            case 14:
                                DangDangOrderDown dang = new DangDangOrderDown(model);
                                dang.SendLogisticsInfo(model);
                                break;
                            case 15:
                                VipShopOrderDown vip = new VipShopOrderDown(model);
                                vip.SendLogisticsInfo(model);
                                break;
                            case 17:
                                SuningOrderDown so = new SuningOrderDown(model);
                                so.SuningCustomOrderDeliveryAdd();
                                break;
                        }
                        isOk = true;
                    }
                    catch (Exception ex)
                    {
                        isOk = false;
                        WriteSysLog.Log("ServerLog", string.Format("订单发货服务运作异常，异常信息{0},异常时间{1}\r\n", ex.Message, System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                isOk = false;
                WriteSysLog.Log("ServerLog", string.Format("订单发货服务运作异常，异常信息{0},异常时间{1}\r\n", ex.Message, System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            }
            finally
            {
                SendGoodsForNotAutoDown();
            }
            return isOk;
        }

    

        /// <summary>
        /// 为手动导入的订单执行发货操作
        /// </summary>
        private void SendGoodsForNotAutoDown()
        {
            bool res = false;
            CocoNut.BLL.OrderDownService.t_ddzb ddzbBll = new CocoNut.BLL.OrderDownService.t_ddzb();
            List<CocoNut.Model.OrderDownService.t_ddzb> modelList = null;
            CocoNut.BLL.OrderDownService.T_ERP_ShopInfo bll = new CocoNut.BLL.OrderDownService.T_ERP_ShopInfo();
            List<CocoNut.Model.OrderDownService.T_ERP_ShopInfo> listModel = new List<CocoNut.Model.OrderDownService.T_ERP_ShopInfo>();
            listModel = bll.GetModelList(" IsAutoDown=0 ");
            foreach (CocoNut.Model.OrderDownService.T_ERP_ShopInfo shopmodel in listModel)
            {
                try
                {
                    modelList = new List<CocoNut.Model.OrderDownService.t_ddzb>();
                    modelList = ddzbBll.GetModelList(string.Format(" dpid='{0}' and bgcz=1 and fh=0 and hb_zt='否' ", shopmodel.ShopNumber.Value));
                    foreach (CocoNut.Model.OrderDownService.t_ddzb model in modelList)
                    {
                        if (model.bgczsj.Length == 0)
                        {
                            model.bgczsj = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        }
                        res = ddzbBll.UpdateLogistStatus(model.id, "1", model.bgczsj);
                        if (res)
                        {
                            DownOrderCommon.WriteLogs("3", string.Format("订单号为{0}已经发货成功[手动导单]！", model.tid), model.dpid);
                        }
                    }
                }
                catch
                {

                }
            }
          

        }

        private void fhToolStripMenuItem_Click(object sender, EventArgs e)
        {
           
        }

        private void 服务重启ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetServiceStatus("1");
        }

        private void 服务停止ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetServiceStatus("0");
        }

   
    }
}
